{% extends "members/base.html" %}

{% block title %}发布管理{% endblock %}

{% block extra_css %}
<style>
.publication-card {
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.publication-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    transform: translateY(-2px);
}

.status-badge {
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
}

.stats-item {
    text-align: center;
    padding: 1rem;
    border-radius: 6px;
    background: #f8f9fa;
}

.stats-number {
    font-size: 1.5rem;
    font-weight: bold;
    color: #007bff;
}

.copy-link-btn {
    cursor: pointer;
    transition: all 0.2s ease;
}

.copy-link-btn:hover {
    background-color: #e9ecef;
}

.publication-actions {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.publication-actions .btn {
    flex: 1;
    min-width: 80px;
}

@media (max-width: 768px) {
    .publication-actions {
        flex-direction: column;
    }
    
    .publication-actions .btn {
        flex: none;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2><i class="bi bi-share me-2"></i>发布管理</h2>
            <p class="text-muted mb-0">管理您发布的系统内置量表</p>
        </div>
        <a href="{{ url_for('members.publish_scale') }}" class="btn btn-primary">
            <i class="bi bi-plus-circle me-2"></i>发布新量表
        </a>
    </div>

    <!-- 统计概览 -->
    <div class="row mb-4">
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="stats-item">
                <div class="stats-number" id="total-publications">-</div>
                <div class="text-muted">总发布数</div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="stats-item">
                <div class="stats-number" id="active-publications">-</div>
                <div class="text-muted">活跃发布</div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="stats-item">
                <div class="stats-number" id="total-access">-</div>
                <div class="text-muted">总访问量</div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="stats-item">
                <div class="stats-number" id="total-assessments">-</div>
                <div class="text-muted">总测评数</div>
            </div>
        </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label">状态筛选</label>
                    <select class="form-select" id="status-filter">
                        <option value="">全部状态</option>
                        <option value="active">活跃</option>
                        <option value="inactive">已停用</option>
                    </select>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">排序方式</label>
                    <select class="form-select" id="sort-by">
                        <option value="created_at">创建时间</option>
                        <option value="access_count">访问量</option>
                        <option value="assessment_count">测评数</option>
                        <option value="last_accessed_at">最后访问</option>
                    </select>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">搜索</label>
                    <input type="text" class="form-control" id="search-input" placeholder="搜索量表标题...">
                </div>
            </div>
            <div class="text-end">
                <button class="btn btn-outline-secondary" onclick="resetFilters()">
                    <i class="bi bi-arrow-clockwise me-1"></i>重置
                </button>
                <button class="btn btn-primary" onclick="loadPublications()">
                    <i class="bi bi-search me-1"></i>搜索
                </button>
            </div>
        </div>
    </div>

    <!-- 发布列表 -->
    <div class="row" id="publications-container">
        <!-- 发布项将通过JavaScript动态加载 -->
    </div>

    <!-- 分页 -->
    <nav aria-label="分页导航" id="pagination-container" class="mt-4">
        <!-- 分页将通过JavaScript动态生成 -->
    </nav>

    <!-- 加载状态 -->
    <div class="text-center py-5" id="loading-indicator">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-2 text-muted">正在加载发布列表...</p>
    </div>

    <!-- 空状态 -->
    <div class="text-center py-5 d-none" id="empty-state">
        <i class="bi bi-inbox display-1 text-muted"></i>
        <h4 class="mt-3 text-muted">暂无发布记录</h4>
        <p class="text-muted">您还没有发布任何量表，<a href="{{ url_for('members.publish_scale') }}">立即发布</a>您的第一个量表吧！</p>
    </div>
</div>

<!-- 编辑发布模态框 -->
<div class="modal fade" id="editPublicationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑发布信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="edit-publication-form">
                    <input type="hidden" id="edit-publication-id">
                    <div class="mb-3">
                        <label class="form-label">自定义标题</label>
                        <input type="text" class="form-control" id="edit-custom-title" maxlength="200">
                        <div class="form-text">留空则使用原量表标题</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">自定义描述</label>
                        <textarea class="form-control" id="edit-custom-description" rows="3" maxlength="500"></textarea>
                        <div class="form-text">留空则使用原量表描述</div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="edit-is-active">
                            <label class="form-check-label" for="edit-is-active">
                                启用发布
                            </label>
                        </div>
                        <div class="form-text">关闭后，访问链接将无法使用</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="savePublication()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 复制链接提示 -->
<div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div id="copy-toast" class="toast" role="alert">
        <div class="toast-header">
            <i class="bi bi-check-circle-fill text-success me-2"></i>
            <strong class="me-auto">复制成功</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            链接已复制到剪贴板
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentPage = 1;
let totalPages = 1;
const perPage = 12;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadPublications();
});

// 加载发布列表
function loadPublications(page = 1) {
    currentPage = page;
    
    // 显示加载状态
    document.getElementById('loading-indicator').style.display = 'block';
    document.getElementById('publications-container').innerHTML = '';
    document.getElementById('pagination-container').innerHTML = '';
    document.getElementById('empty-state').classList.add('d-none');
    
    // 构建查询参数
    const params = new URLSearchParams({
        page: page,
        per_page: perPage
    });
    
    // 添加筛选参数
    const statusFilter = document.getElementById('status-filter').value;
    const sortBy = document.getElementById('sort-by').value;
    const searchInput = document.getElementById('search-input').value;
    
    if (statusFilter) params.append('status', statusFilter);
    if (sortBy) params.append('sort_by', sortBy);
    if (searchInput) params.append('search', searchInput);
    
    apiRequest(`/api/scales/my-publications?${params.toString()}`)
        .then(response => {
            if (response.code === 200) {
                displayPublications(response.data.publications);
                updatePagination(response.data.pagination);
                updateStats(response.data.publications);
            } else {
                throw new Error(response.message || '加载失败');
            }
        })
        .catch(error => {
            console.error('加载发布列表失败:', error);
            showResult(false, '加载发布列表失败: ' + error.message);
        })
        .finally(() => {
            document.getElementById('loading-indicator').style.display = 'none';
        });
}

// 显示发布列表
function displayPublications(publications) {
    const container = document.getElementById('publications-container');
    
    if (publications.length === 0) {
        document.getElementById('empty-state').classList.remove('d-none');
        return;
    }
    
    container.innerHTML = publications.map(pub => `
        <div class="col-lg-6 col-xl-4 mb-4">
            <div class="card publication-card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-3">
                        <h6 class="card-title mb-0">
                            ${pub.custom_title || pub.scale.title}
                        </h6>
                        <span class="badge ${pub.is_active ? 'bg-success' : 'bg-secondary'} status-badge">
                            ${pub.is_active ? '活跃' : '已停用'}
                        </span>
                    </div>
                    
                    <p class="text-muted small mb-3">
                        原量表：${pub.scale.title}
                    </p>
                    
                    ${pub.custom_description ? `
                        <p class="card-text small text-muted mb-3">
                            ${pub.custom_description.length > 100 ? 
                                pub.custom_description.substring(0, 100) + '...' : 
                                pub.custom_description}
                        </p>
                    ` : ''}
                    
                    <div class="row text-center mb-3">
                        <div class="col-4">
                            <div class="small text-muted">访问量</div>
                            <div class="fw-bold text-primary">${pub.access_count}</div>
                        </div>
                        <div class="col-4">
                            <div class="small text-muted">测评数</div>
                            <div class="fw-bold text-success">${pub.assessment_count}</div>
                        </div>
                        <div class="col-4">
                            <div class="small text-muted">转化率</div>
                            <div class="fw-bold text-info">
                                ${pub.access_count > 0 ? 
                                    Math.round((pub.assessment_count / pub.access_count) * 100) + '%' : 
                                    '0%'}
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="input-group input-group-sm">
                            <input type="text" class="form-control" value="${pub.public_url}" readonly>
                            <button class="btn btn-outline-secondary copy-link-btn" 
                                    onclick="copyLink('${pub.public_url}')" 
                                    title="复制链接">
                                <i class="bi bi-clipboard"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="publication-actions">
                        <button class="btn btn-sm btn-outline-primary" 
                                onclick="editPublication(${pub.id})">
                            <i class="bi bi-pencil"></i> 编辑
                        </button>
                        <button class="btn btn-sm btn-outline-info" 
                                onclick="viewDetails(${pub.id})">
                            <i class="bi bi-eye"></i> 详情
                        </button>
                        <button class="btn btn-sm btn-outline-danger" 
                                onclick="deletePublication(${pub.id})">
                            <i class="bi bi-trash"></i> 删除
                        </button>
                    </div>
                </div>
                
                <div class="card-footer bg-transparent">
                    <small class="text-muted">
                        <i class="bi bi-calendar me-1"></i>
                        创建于 ${formatDate(pub.created_at)}
                        ${pub.last_accessed_at ? 
                            `<br><i class="bi bi-clock me-1"></i>最后访问 ${formatDate(pub.last_accessed_at)}` : 
                            ''}
                    </small>
                </div>
            </div>
        </div>
    `).join('');
}

// 更新统计信息
function updateStats(publications) {
    const totalPublications = publications.length;
    const activePublications = publications.filter(p => p.is_active).length;
    const totalAccess = publications.reduce((sum, p) => sum + p.access_count, 0);
    const totalAssessments = publications.reduce((sum, p) => sum + p.assessment_count, 0);
    
    document.getElementById('total-publications').textContent = totalPublications;
    document.getElementById('active-publications').textContent = activePublications;
    document.getElementById('total-access').textContent = totalAccess;
    document.getElementById('total-assessments').textContent = totalAssessments;
}

// 更新分页
function updatePagination(pagination) {
    totalPages = pagination.pages;
    const container = document.getElementById('pagination-container');
    
    if (totalPages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    let paginationHtml = '<ul class="pagination justify-content-center">';
    
    // 上一页
    paginationHtml += `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadPublications(${currentPage - 1})">
                <i class="bi bi-chevron-left"></i>
            </a>
        </li>
    `;
    
    // 页码
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            paginationHtml += `
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="loadPublications(${i})">${i}</a>
                </li>
            `;
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            paginationHtml += '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
    }
    
    // 下一页
    paginationHtml += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadPublications(${currentPage + 1})">
                <i class="bi bi-chevron-right"></i>
            </a>
        </li>
    `;
    
    paginationHtml += '</ul>';
    container.innerHTML = paginationHtml;
}

// 复制链接
function copyLink(url) {
    navigator.clipboard.writeText(url).then(() => {
        const toast = new bootstrap.Toast(document.getElementById('copy-toast'));
        toast.show();
    }).catch(err => {
        console.error('复制失败:', err);
        // 降级方案
        const textArea = document.createElement('textarea');
        textArea.value = url;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        
        const toast = new bootstrap.Toast(document.getElementById('copy-toast'));
        toast.show();
    });
}

// 编辑发布
function editPublication(publicationId) {
    // 从当前列表中找到对应的发布
    const publications = Array.from(document.querySelectorAll('.publication-card')).map((card, index) => {
        // 这里需要从API重新获取数据，简化处理
        return null;
    });
    
    // 获取发布详情
    apiRequest(`/api/members/scale-publications/${publicationId}/detail`)
        .then(response => {
            if (response.code === 200) {
                const pub = response.data;
                document.getElementById('edit-publication-id').value = pub.id;
                document.getElementById('edit-custom-title').value = pub.custom_title || '';
                document.getElementById('edit-custom-description').value = pub.custom_description || '';
                document.getElementById('edit-is-active').checked = pub.is_active;
                
                const modal = new bootstrap.Modal(document.getElementById('editPublicationModal'));
                modal.show();
            } else {
                throw new Error(response.message || '获取发布信息失败');
            }
        })
        .catch(error => {
            console.error('获取发布信息失败:', error);
            showResult(false, '获取发布信息失败: ' + error.message);
        });
}

// 保存发布修改
function savePublication() {
    const publicationId = document.getElementById('edit-publication-id').value;
    const customTitle = document.getElementById('edit-custom-title').value.trim();
    const customDescription = document.getElementById('edit-custom-description').value.trim();
    const isActive = document.getElementById('edit-is-active').checked;
    
    const data = {
        custom_title: customTitle || null,
        custom_description: customDescription || null,
        is_active: isActive
    };
    
    apiRequest(`/api/members/scale-publications/${publicationId}`, {
        method: 'PUT',
        body: JSON.stringify(data)
    })
    .then(response => {
        if (response.code === 200) {
            showResult(true, '更新成功', () => {
                const modal = bootstrap.Modal.getInstance(document.getElementById('editPublicationModal'));
                modal.hide();
                loadPublications(currentPage);
            });
        } else {
            throw new Error(response.message || '更新失败');
        }
    })
    .catch(error => {
        console.error('更新发布失败:', error);
        showResult(false, '更新失败: ' + error.message);
    });
}

// 查看详情
function viewDetails(publicationId) {
    window.location.href = `{{ url_for('members.publication_detail', publication_id=0) }}`.replace('0', publicationId);
}

// 删除发布
function deletePublication(publicationId) {
    if (!confirm('确定要删除这个发布吗？删除后将无法恢复，且访问链接将失效。')) {
        return;
    }
    
    apiRequest(`/api/members/scale-publications/${publicationId}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (response.code === 200) {
            showResult(true, '删除成功', () => {
                loadPublications(currentPage);
            });
        } else {
            throw new Error(response.message || '删除失败');
        }
    })
    .catch(error => {
        console.error('删除发布失败:', error);
        showResult(false, '删除失败: ' + error.message);
    });
}

// 重置筛选
function resetFilters() {
    document.getElementById('status-filter').value = '';
    document.getElementById('sort-by').value = 'created_at';
    document.getElementById('search-input').value = '';
    loadPublications(1);
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 搜索框回车事件
document.getElementById('search-input').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        loadPublications(1);
    }
});
</script>
{% endblock %}